package com.atguigu.order.orders.interceptor;


import com.atguigu.common.to.AutoLoginResponse;
import com.atguigu.common.to.UmsMemberEntity;
import org.apache.shiro.util.AntPathMatcher;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Configuration
public class OrderInterceptor implements HandlerInterceptor {

    //定义local
    public static ThreadLocal<UmsMemberEntity> local=new ThreadLocal<>();
    /**
     * 请求之前执行
     *
     * @param request
     * @param response
     * @param handler
     * @return
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {


        //放行所有库存远程请求
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/orders/**", uri);
        if(match){
            return true;
        }
        //判断是否登录
        HttpSession session = request.getSession();
        UmsMemberEntity memberEntity = (UmsMemberEntity) session.getAttribute(AutoLoginResponse.REDIS_SESSION_LOGIN);
        if (memberEntity == null) {
            response.sendRedirect("http://auth.gulimail.com/login.html");
            return false;
        }
        //登录将用户放入local中
        local.set(memberEntity);
        return true;
    }

    /**
     * 之后执行
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }
}
